﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using JPGResizer.Model;
using System.Collections.ObjectModel;
using System.IO;

namespace JPGResizer.Pages
{
    /// <summary>
    /// Interaction logic for Page1.xaml
    /// </summary>
    public partial class Page1 : Page
    {
        #region Constructors

        public Page1()
        {
            InitializeComponent();
            Bind_Events();
        }

        private void Bind_Events()
        {
            this.Loaded += (o, e) =>
                {
                    this.ParentPath = string.Empty;
                    Bind_Datas();
                };
            this.lstFiles.KeyUp += (o, e) =>
                {
                    if (this.lstFiles.IsFocused && this.lstFiles.SelectedItem != null && e.Key == Key.Delete)
                    {
                        MyImage img = this.lstFiles.SelectedItem as MyImage;
                        if (img != null && Helper.ValueHelper.CurrentValues.Images.Contains(img))
                        {
                            Helper.ValueHelper.CurrentValues.Images.Remove(img);
                        }
                    }
                };
        } 

        #endregion
        
        /// <summary>
        /// 当前的所选路径
        /// </summary>
        private string ParentPath { get; set; }

        private void SelectFolder_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog fbDialog = new System.Windows.Forms.FolderBrowserDialog();

            if (fbDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                DirectoryInfo di = new DirectoryInfo(fbDialog.SelectedPath);
                foreach (FileInfo fileinfo in di.GetFiles("*.jpg"))
                {
                    InsertImage(fileinfo.FullName, true);
                }
                foreach (DirectoryInfo dirinfo in di.GetDirectories())
                {
                    GetImages(dirinfo.FullName);
                }
            }
            Bind_Datas();
        }
        #region 从文件夹取图片

        private void GetImages(string directory)
        {
            DirectoryInfo di = new DirectoryInfo(directory);

            foreach (FileInfo fileinfo in di.GetFiles("*.jpg"))
            {
                InsertImage(fileinfo.FullName, false);
            }
            foreach (DirectoryInfo dirinfo in di.GetDirectories())
            {
                GetImages(dirinfo.FullName);
            }
        }  
        #endregion

        private void SelectFile_Click(object sender, RoutedEventArgs e)
        {
            // Configure open file dialog box
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.FileName = "图片文件"; // Default file name
            dlg.DefaultExt = ".jpg"; // Default file extension
            dlg.Filter = "JPEG Files (.jpg)|*.jpg"; // Filter files by extension

            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results
            if (result == true)
            {
                Helper.ValueHelper.CurrentValues.Images = new ObservableCollection<MyImage>();
                // Open document
                InsertImage(dlg.FileName,true);
                Bind_Datas();

            }

        }


        #region 数据相关

        private void Bind_Datas()
        {
            //有三种类型的图片
            //1.出于根目录下的
            //2.子文件夹下的
            //3.不在根目录已经任意文件夹下的——因为我们不能保证用户是否会多次添加图片
            this.lstFiles.ItemsSource = Helper.ValueHelper.CurrentValues.Images;
        }

        private void InsertImage(string fullFilename, bool isRoot)
        {
            string filename = Helper.ValueHelper.CurrentValues.GetFilenameFromFullPath(fullFilename);
            string filefullpath = fullFilename.Replace("\\" + filename, "");
            if (isRoot //根目录下的图片
                || string.IsNullOrEmpty(this.ParentPath) //在这之前根本没有记载根目录是多少，所以以当前图片的路径为根目录
                || !filefullpath.Contains(this.ParentPath)//文件的完整路径中不包含以前所记载的根目录，因此这是一个全新的集合
                )
            {
                this.ParentPath = filefullpath;
                InsertImage(fullFilename, filename, filefullpath, string.Empty);
            }
            else
            {
                string filepath = filefullpath.Replace(this.ParentPath, "");
                InsertImage(fullFilename, filename, filefullpath, filepath);
            }
        }



        private static void InsertImage(string fullFilename, string filename, string filefullpath, string filepath)
        {
            try
            {
                Helper.ValueHelper.CurrentValues.Images.Add(new MyImage(new BitmapImage(new Uri(fullFilename)), filename, filepath, filefullpath));
            }
            catch(Exception ex)
            {
                Helper.ErrorHelper.ErrorHandler(ex);
            }
        } 

        #endregion
    }
}
